<?php

namespace app\common\model\tysj;

class Product extends CUBase {
	protected $privacyFields = ['status','examine_after_status', 'examine', 'updatetime'];
    protected $append = ['photo_url', 'product_classify', 'is_show', 'is_examine', 'collect_id', 'is_group_buying', 'area_id'];
    protected $hidden = [];
    protected $isPhotoFile = false;//是否返回图片整个数据

	protected static function init()
    {
        parent::init();

        // 注册 before_insert 事件
        self::beforeInsert(function ($data) {
        	$status = loadEnum('ProductStatus');
        	$examine = loadEnum('ProductExamine');
            $data['status'] = $status->hideStatus();
            $data['examine'] = $examine->prepare();
            if(!isset($data['examine_after_status'])) {
                $data['examine_after_status'] = $data['status'];
            }
            return $data;
        });
    }

    //重置产品状态
    public function reset($id = null) {
    	$status = loadEnum('Status');
        $examine = loadEnum('StoreExamine');
    	if(!$id) {
    		$id = $this->id;
    	}
    	$data = [];
    	$data['status'] = $status->hideStatus();
        $data['examine'] = $examine->prepare();
    	$this->where(['id' => $id])->update($data);
    	return $this;
    }

    //修改是否返回图片整个数据
    public function setPhotoFile($isPhotoFile) {
        $this->isPhotoFile = $isPhotoFile;
        return $this;
    }

    //店铺数据关联
    public function store() {
        return $this->hasOne('Store', 'id', 'sid');
    }

    //主图文件关联
    public function photoFile() {
        return $this->hasOne('Image', 'id', 'photo');
    }

    //图片关联关系表
    public function photosFile()
    {
        $enum = loadEnum('ProductImageType');
        return $this->hasMany('ProductImageNexus', 'pid', 'id')->where(['type' => $enum->code2key('pic')]);
    }

    //规格关联规格表
    public function specs() {
        return $this->hasMany('ProductSpecsNexus', 'pid', 'id');
    }

    //审核后产品状态
    public function getExamineAfterStatusTextAttr() {
        $status = loadEnum('ProductStatus');
        $options = $status->get_options();
        return $options[$this->getData('examine_after_status')];
    }

    //图片详情关联关系表
    public function infoPhotosFile()
    {
        $enum = loadEnum('ProductImageType');
        return $this->hasMany('ProductImageNexus', 'pid', 'id')->where(['type' => $enum->code2key('info')]);
    }

    //获取店铺名称
    public function getStoreNameAttr($value, $data) {
        $store = loadOnly('tysj\\Store')->find('tysj\\Store', $data['sid']);
        return $store ? $store['name'] : '';
    }

    //获取产品最低价格
    public function getPriceAttr() {
        $row = loadModel('tysj\\ProductSpecsNexus')->alias('PSN')->join('ProductSpecs PS', 'PSN.psid = PS.id', 'left')->where(['PSN.pid' => $this->id])->order('PS.price asc')->field('PS.price')->find();
        return $row ? $row['price'] : '';
    }

    //获取产品图片地址数组
    public function getPhotoUrlAttr($value, $data) {
        $row  = loadModel('tysj\\Image')->where(['id' => $data['photo']])->find();
        if(!$this->isPhotoFile) {
            return isset($row['url']) ? $row['url'] : '';
        }
        return $row;
    }

    //获取产品图片地址数组
    public function getPhotosUrlAttr($value, $data) {
        $enum = loadEnum('ProductImageType');
        $model = loadModel('tysj\\ProductImageNexus')->alias('PIN')->join('Image I', 'PIN.iid = I.id', 'left')->where(['PIN.pid' => $data['id'], 'PIN.type' => $enum->code2key('pic')]);
        if($this->isPhotoFile) {
            return $model->select();
        } else {
            return $model->column('I.url');
        }
    }

    //获取产品详情图片地址数组
    public function getInfoPhotosUrlAttr($value, $data) {
        $enum = loadEnum('ProductImageType');
        $model = loadModel('tysj\\ProductImageNexus')->alias('PIN')->join('Image I', 'PIN.iid = I.id', 'left')->where(['PIN.pid' => $data['id'], 'PIN.type' => $enum->code2key('info')]);
        if($this->isPhotoFile) {
            return $model->select();
        } else {
            return $model->column('I.url');
        }
    }

    //获取产品分类
    public function getProductClassifyAttr($value, $data) {
        if(!isset($data['cid'])) {
            return null;
        }
        return loadModel('tysj\\ProductClassify')->where(['id' => $data['cid']])->find()['name'];
    }

    //获取产品售后规则
    public function getOstSaleAttr($value, $data) {
        return loadModel('tysj\\OstSale')->where(['id' => $data['osid']])->find()['name'];
    }

    //返回状态文本信息
    public function getStatusTextAttr() {
        $status = loadEnum('ProductStatus');
        $options = $status->get_options();
        return $options[$this->getData($this->statusKey)];
    }

    //返回审核状态文本信息
    public function getExamineTextAttr() {
        $examine = loadEnum('ProductExamine');
        $options = $examine->get_options();
        return $options[$this->getData($this->examineKey)];
    }

    //获取审核记录
    public function getExamineLogAttr() {
        return loadModel('tysj\\ProductExamineLog')->where(['pid' => $this->id])->field('remark,createtime')->find();
    }

    //获取规格记录
    public function getSpecsListAttr() {
        return loadModel('tysj\\ProductSpecsNexus')->alias('PSN')->join('ProductSpecs PS', 'PSN.psid = PS.id', 'left')->where(['PSN.pid' => $this->id])->field('PS.*')->select();
    }

    //获取关键字
    public function getKeywordAttr() {
        return loadModel('tysj\\ProductKeywordNexus')->alias('PKN')->join('ProductKeyword PK', 'PKN.pkid = PK.id', 'left')->where(['PKN.pid' => $this->id])->field('PS.*')->column('name');
    }

    //获取佣金范围
    public function getCommissionAttr() {
        $arr = loadModel('tysj\\ProductSpecsNexus')->alias('PSN')->join('ProductSpecs PS', 'PSN.psid = PS.id', 'left')->where(['PSN.pid' => $this->id])->column('PS.commission');
        return ['min' => min($arr), 'max' => max($arr)]; 
    }

    //获取收藏ID
    public function getCollectIdAttr($value, $data) {
        $user = loadStorage('Login')->getCurrentUser();
        $row = null;
        if($user) {
            $row =loadModel('tyyh\\Collect')->where(['pid' => $data['id'], 'uid' => $user['id']])->find();
        }
        if(empty($row)) {
            return null;
        }
        return $row['id'];
    }

    //获取产品是否是团购产品
    public function getIsGroupBuyingAttr($value, $data) {
        $row = loadModel('tysj\\ProductGroupBuying')->where(['pid' => $data['id']])->find();
        return $row ? true : false;
    }

    //获取产品的土特产分类
    public function getAreaIdAttr($value, $data) {
        $row = loadModel('tysj\\NativeProduct')->where(['pid' => $data['id']])->find();
        return $row ? $row['areaid'] : 0;
    }

    //删除产品相关信息
    public function delAll($id) {
        try {
            $this->startTrans();
            loadModel('tysj\\ProductExamineLog')->where(['pid' => $id])->delete();
            loadModel('tysj\\ProductImageNexus')->where(['pid' => $id])->delete();
            loadModel('tysj\\ProductSpecsNexus')->where(['pid' => $id])->delete();
            loadModel('tysj\\ProductKeywordNexus')->where(['pid' => $id])->delete();
            $this->where(['id' => $id])->delete();
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw $e;
        }
    }
}